package hivi.vn.hivigold.activities;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.database.Preferences;
import hivi.vn.hivigold.database.WebService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

public class SelectTable extends Activity {

	public JSONObject[] objNhVv, objVv;
	public String[] objStatusPh81, objRecPh81;
	public Button[] btnNhvv, btnVv;
	public LinearLayout lleft;

	@SuppressLint("InlinedApi")
	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		this.requestWindowFeature(Window.FEATURE_ACTION_BAR);
		setContentView(R.layout.selectable_layout);

		String resultNhvv = WebService.getData(this, "dmnhvv", "Status=1",
				"NhvvID,NhvvName");
		try {
			final Drawable drawableTopNhVv = getResources().getDrawable(
					R.drawable.food);
			JSONArray json = new JSONArray(resultNhvv);
			btnNhvv = new Button[json.length()];
			objNhVv = new JSONObject[json.length()];
			lleft = (LinearLayout) findViewById(R.id.layoutleft);
			LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, 1.0f);
			param.setMargins(5, 20, 5, 5);
			for (int i = 0; i < json.length(); i++) {
				objNhVv[i] = json.getJSONObject(i);
				btnNhvv[i] = new Button(getApplicationContext());
				btnNhvv[i].setText(objNhVv[i].getString("NhvvName"));
				btnNhvv[i].setId(i);
				btnNhvv[i].setBackgroundColor(Color.parseColor("#4197ee"));
				btnNhvv[i].setLayoutParams(param);
				btnNhvv[i].setPadding(15, 5, 15, 5);
				btnNhvv[i].setCompoundDrawablesWithIntrinsicBounds(null,
						drawableTopNhVv, null, null);
				lleft.addView(btnNhvv[i]);
				btnNhvv[i].setOnClickListener(handleOnClick(btnNhvv[i], this,
						lleft));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);

		if (Preferences.getPreferenceValue(getBaseContext(),
				Preferences.SELECTEDTABLEAREAPOSITION) == null)
			clickNhvv(btnNhvv[0], this, lleft);
		else
			try {

				clickNhvv(btnNhvv[Integer.parseInt(Preferences
						.getPreferenceValue(getBaseContext(),
								Preferences.SELECTEDTABLEAREAPOSITION))], this,
						lleft);
			} catch (Exception e) {
				clickNhvv(btnNhvv[0], this, lleft);
			}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		 getMenuInflater().inflate(R.menu.main, menu);
	     return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		  switch (item.getItemId()) {
		    case R.id.action_settings:
		      SettingActivities.onStartIntent(this);
		      return true;
		    default:
		      return super.onOptionsItemSelected(item);
		  }
		}

	public View.OnClickListener handleOnClick(final Button button,
			final Context c, final LinearLayout ll) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				clickNhvv(button, c, ll);
			}
		};
	}

	public View.OnClickListener handleOnClickVv(final Button button,
			final Context c) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				clickVv(button, c);
			}
		};
	}

	private void clickNhvv(Button button, Context c, LinearLayout ll) {
		for (int i = 0; i < btnNhvv.length; i++) {
			btnNhvv[i].setBackgroundColor(Color.parseColor("#4197ee"));
		}
		button.setBackgroundColor(Color.parseColor("#ce0100"));
		String condition = "", NhvvID = "", NhvvName = "";
		try {
			NhvvID = objNhVv[button.getId()].getString("NhvvID");
			NhvvName = objNhVv[button.getId()].getString("NhvvName");
			condition = "FK_NhvvID = '" + NhvvID + "'";
			Preferences.editPreferenceValue(c, Preferences.SELECTEDTABLEAREAID,
					NhvvID);
			Preferences.editPreferenceValue(c,
					Preferences.SELECTEDTABLEAREANAME, NhvvName);
			Preferences.editPreferenceValue(c,
					Preferences.SELECTEDTABLEAREAPOSITION, "" + button.getId());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		String resultVv = WebService.getData(c, "dmvv", condition,
				"VvID,VvName");
		try {
			final Drawable drawableTopVv = getResources().getDrawable(
					R.drawable.table);
			JSONArray json = new JSONArray(resultVv);
			btnVv = new Button[json.length()];
			objVv = new JSONObject[json.length()];
			LinearLayout lright = (LinearLayout) findViewById(R.id.layoutright);
			LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, 1.0f);
			objStatusPh81 = new String[json.length()];
			objRecPh81 = new String[json.length()];
			for (int i = 0; i < json.length(); i++) {
				objVv[i] = json.getJSONObject(i);
				btnVv[i] = new Button(getApplicationContext());
				btnVv[i].setText(objVv[i].getString("VvName"));
				btnVv[i].setId(i);
				btnVv[i].setBackgroundColor(Color.parseColor("#77d42a"));
				btnVv[i].setLayoutParams(param);
				btnVv[i].setPadding(15, 5, 15, 5);
				btnVv[i].setOnClickListener(handleOnClickVv(btnVv[i], c));
				btnVv[i].setBackgroundColor(getResources().getColor(
						R.color.color_green));
				btnVv[i].setCompoundDrawablesWithIntrinsicBounds(null,
						drawableTopVv, null, null);
				String conditionPh81 = "FK_VvID = '"
						+ objVv[i].getString("VvID")
						+ "' and FK_CtID = 'HDA' and Status='0'";
				String resultPh81 = WebService.getData(c, "ph81",
						conditionPh81, "Stt_rec");
				JSONArray jsonPh81 = new JSONArray(resultPh81);
				if (jsonPh81.length() > 0) {
					btnVv[i].setBackgroundColor(getResources().getColor(
							R.color.color_red));
					objStatusPh81[i] = "0";
					objRecPh81[i] = jsonPh81.getJSONObject(0).getString(
							"Stt_rec");
				} else {
					objStatusPh81[i] = "1";
					objRecPh81[i] = "";
				}
			}
			populateText(lright, btnVv, c, ll);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void clickVv(Button button, Context c) {
		try {
			Preferences.editPreferenceValue(c, Preferences.SELECTEDTABLEID,
					objVv[button.getId()].getString("VvID"));
			Preferences.editPreferenceValue(c, Preferences.SELECTEDTABLENAME,
					objVv[button.getId()].getString("VvName"));
			Preferences.editPreferenceValue(c, Preferences.SELECTEDTABLESTATUS,
					objStatusPh81[button.getId()]);
			Preferences.editPreferenceValue(c, Preferences.SELECTEDTABLESTTREC,
					objRecPh81[button.getId()]);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		SelectDish.onStartIntent(getBaseContext());
	}

	/**
	 * hien thi tren linearlayout theo nhieu dong
	 * 
	 * @param ll
	 *            : linearlayout
	 * @param views
	 *            : views can add vao linerlayout
	 * @param mContext
	 */
	@SuppressWarnings({ "deprecation" })
	private void populateText(LinearLayout ll, View[] views, Context mContext,
			LinearLayout ll1) {
		Display display = getWindowManager().getDefaultDisplay();
		ll.removeAllViews();
		int maxWidth = display.getWidth() - ll1.getMeasuredWidth() - 80;
		LinearLayout.LayoutParams params;
		LinearLayout newLL = new LinearLayout(mContext);
		newLL.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
		newLL.setGravity(Gravity.LEFT);
		newLL.setOrientation(LinearLayout.HORIZONTAL);

		int widthSoFar = 0;

		for (int i = 0; i < views.length; i++) {
			LinearLayout LL = new LinearLayout(mContext);
			LL.setOrientation(LinearLayout.HORIZONTAL);
			LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
			views[i].measure(0, 0);
			params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(),
					LayoutParams.WRAP_CONTENT);
			params.setMargins(5, 5, 5, 5);
			LL.addView(views[i], params);
			LL.measure(0, 0);
			widthSoFar += views[i].getMeasuredWidth();
			if (widthSoFar >= maxWidth) {
				ll.addView(newLL);

				newLL = new LinearLayout(mContext);
				newLL.setLayoutParams(new LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				newLL.setOrientation(LinearLayout.HORIZONTAL);
				newLL.setGravity(Gravity.LEFT);
				params = new LinearLayout.LayoutParams(LL.getMeasuredWidth(),
						LL.getMeasuredHeight());
				newLL.addView(LL, params);
				widthSoFar = LL.getMeasuredWidth();
			} else {
				newLL.addView(LL);
			}
		}
		ll.addView(newLL);
	}

	public static void onStartIntent(Context c) {
		Intent i = new Intent(c, SelectTable.class);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		c.startActivity(i);
	}
}
